package com.kjlink.internal.report4vue.config.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import com.kjlink.internal.workreport.helper.SessionHelper;
import com.kjlink.internal.workreport.user.model.User;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 描述:
 *
 * @author Vic.xu
 * @since 2024-11-22 16:56
 */
public class ApiTokenInterceptor implements AsyncHandlerInterceptor {
    /**
     * https://sa-token.cc/doc.html#/use/login-auth
     * https://blog.csdn.net/weixin_43982359/article/details/131823090
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean login = StpUtil.isLogin();
        if (login) {
            return true;
        }
        User user = SessionHelper.currentUser();

        if (user != null) {
            return true;
        }
        to401(response);
        return false;
    }


    private void to401(HttpServletResponse response) throws IOException {
        // 设置 401 状态码
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write("Unauthorized: Missing or invalid token");
    }


    /**
     * 获取请求头中的token
     * 前端如此：   Authorization: token ? `Bearer ${token}` : undefined,
     */
    public String getToken(HttpServletRequest request) {
        String authorizationHeader = request.getHeader("Authorization");
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            // 去掉 "Bearer " 前缀
            return authorizationHeader.substring(7);
        }
        return null;
    }
}
